import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 用Lock来解决买票问题
 */
public class SellTicket02 {
    public static void main(String[] args) {
        Ticket02 ticket = new Ticket02();
        new Thread(() -> { for (int i = 0; i < 80; i++) ticket.sale(); }, "小明").start();
        new Thread(() -> { for (int i = 0; i < 80; i++) ticket.sale(); }, "大刘").start();
        new Thread(() -> { for (int i = 0; i < 80; i++) ticket.sale(); }, "胖子").start();
    }
}
/**
 * NonfairSync 非公平锁：也就是没有先后顺序，看CPU心情（调度顺序）
 * FairSync 公平锁，进行排队，先来的（等待时间久的）先执行，后来的（等待时间短的）后执行
 */
class Ticket02 {
    //1.new lock
    private Lock lock = new ReentrantLock();
    private int count = 250;

    public void sale() {
        //2.加锁
        lock.lock();
        //3.加try catch finally
        try {
            //业务代码
            if (count > 0) {
                System.out.println(Thread.currentThread().getName() + "买了第" + (count--) + "张票，剩余" + count + "张票。");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
